#define _GNU_SOURCE 

#include "syscore.h"
#include "apis.h"
#include "common.h"

#include <time.h>

#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include <string.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

#include <sys/io.h>
#include <fcntl.h>

#include <sys/ioctl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/if.h>
#include <ctype.h>
#include <errno.h>
#include <signal.h>
pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;
typedef struct tagPHONEINFO {
    U32 totallen;
    U64 uptime;
    int slotId;
    char imsi[16];
    char imei[16];
    char tmsi[12];
} PHONEINFO;
#define MAX_RECORD 20
#define MAX_RECORD_TIME  1200
#ifdef HTTP
typedef struct tagPHONEINFOUPLOADCTRL {
    FILE *fp;
    char devMac[18];
    char srcMac[18];
    char uploadMac[14];
    char fileName[128];
    char uploadAddr[128];
    char sign[128];
    char url[128];
    char uploadUrl[128];
    char tarName[128];
    char filelist[MAX_RECORD][128];
    char protocol[16];
    char dataType[16];
    char place[16];
    char md5Key[128];
    int listSize;
}PHONEINFOUPLOADCTRL;
#endif
#ifdef FTP
typedef struct tagPHONEINFOUPLOADCTRL {
    FILE *fp;
    char devMac[18];
    char devId[18];
    char Mac[14];
    char addr[128];
    char port[16];
    char usr[128];
    char pwd[128];
    char commond[128];
    char fileName[128];
    U64  startTm; 
}PHONEINFOUPLOADCTRL;

#endif
typedef struct tagDBDESC {
    U64 range_begin;
    U64 range_end;
} DBDESC;

#define DATAUPLOAD_TIMER_RESOLUTION 1000
#ifdef HTTP
#define UPLOADCTRL_TIMEOUT 120000
#endif
#ifdef FTP
#define UPLOADCTRL_TIMEOUT 20000
#endif
PHONEINFOUPLOADCTRL phoneInfoUploadCtrl;
void *DataUploadTimer = NULL;

extern char* data_storage_path;  
static char *upload_path = "/upload";
char recordDir[PATH_MAX] ;
char recordpath[PATH_MAX];

extern PARADECODERMAP UEIDReportTable[4];
static sem_t sem_upload;
RESULT DATAUPLOAD_getMAC(char* name, char* mac, char *uploadMac)
{
    int sockfd;
    struct ifreq tmp;   
    char devMac[20] = {0};
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if( sockfd < 0)
    {
        perror("create socket fail\n");
        return RC_FAIL;
    }

    memset(&tmp,0,sizeof(struct ifreq));
    strncpy(tmp.ifr_name,name,sizeof(tmp.ifr_name)-1);
    if( (ioctl(sockfd,SIOCGIFHWADDR,&tmp)) < 0 )
    {
        dbgprintf(DEBUG_ERROR,stderr,"mac ioctl for %s error\n",name);
        close(sockfd);
        return RC_FAIL;
    }
    close(sockfd);
        

  /*  sprintf(mac, "%02x:%02x:%02x:%02x:%02x:%02x",
            (unsigned char)tmp.ifr_hwaddr.sa_data[0],
            (unsigned char)tmp.ifr_hwaddr.sa_data[1],
            (unsigned char)tmp.ifr_hwaddr.sa_data[2],
            (unsigned char)tmp.ifr_hwaddr.sa_data[3],
            (unsigned char)tmp.ifr_hwaddr.sa_data[4],
            (unsigned char)tmp.ifr_hwaddr.sa_data[5]
            );*/
    sprintf(devMac, "%02x%02x%02x%02x%02x%02x",
            (unsigned char)tmp.ifr_hwaddr.sa_data[0],
            (unsigned char)tmp.ifr_hwaddr.sa_data[1],
            (unsigned char)tmp.ifr_hwaddr.sa_data[2],
            (unsigned char)tmp.ifr_hwaddr.sa_data[3],
            (unsigned char)tmp.ifr_hwaddr.sa_data[4],
            (unsigned char)tmp.ifr_hwaddr.sa_data[5]
            );
    int i = 0, j = 0;
    for (; i < 12; i++)
    {
        uploadMac[i] = toupper(devMac[i]);
        mac[j++] =  toupper(devMac[i]);
        if ( i%2 != 0 && i != 0 && i != 11)
        {
             mac[j++] = ':';
        }
    }
    

    printf("local mac:%s\n", mac);

    return RC_OK;
}

bool DATAUPLOAD_cmdRsp(const char *cmd, int type ,  char *data)
{
    FILE *fpipe = (FILE*)popen(cmd, "r");
  
    if (fpipe == NULL)
    {
       dbgprintf(DEBUG_ERROR,stderr,"can not popen %s\n", cmd);
       return false;
    }
    char rspdata[128] = {0};
    while( NULL != fgets(rspdata, 128, fpipe))
    {
        strcat(data,rspdata);
        memset(rspdata, 0, 128);
        if (strlen(data) > 896)
           break;
    }
    if (strlen(data) == 0)
    {
        pclose(fpipe);
        return false;
    }
    if (type == 0)
    {

        if (strlen(data) != 0)
        {
            int i = 1; 
            for (; i < strlen(data) -1 ; i++)
            {
                data[i -1] = data[i];
            }
        
           
        }
    }
    pclose(fpipe);
    dbgprintf(DEBUG_INFO,stdout,"%s reponse is %s \n", cmd, data);
    return true;
   

}

static BOOL needPostProc = FALSE;
#ifdef HTTP
RESULT DATAUPLOAD_openFile()
{
    time_t now;
    time(&now);
    if (strlen(phoneInfoUploadCtrl.place) <= 5)
        return RC_FAIL;
    memset(phoneInfoUploadCtrl.fileName, 0, 128);
    sprintf(phoneInfoUploadCtrl.fileName, "%s_%s-%12s-%s-%lu", phoneInfoUploadCtrl.dataType, phoneInfoUploadCtrl.protocol, phoneInfoUploadCtrl.uploadMac, phoneInfoUploadCtrl.place, now);
    memset(recordpath, 0, PATH_MAX);
    sprintf(recordpath, "%s/%s.log", recordDir, phoneInfoUploadCtrl.fileName);
    phoneInfoUploadCtrl.fp = fopen(recordpath, "a");
    if (phoneInfoUploadCtrl.fp == NULL)
    {
        dbgprintf(DEBUG_ERROR, stderr, "can not open file  %s \n", recordpath);
        return RC_FAIL;
    }
    pthread_mutex_lock(&counter_mutex);
    phoneInfoUploadCtrl.listSize++;
    if (phoneInfoUploadCtrl.listSize > MAX_RECORD)
    {
        char cmd[128] = {0};
        sprintf(cmd, "rm %s/%s.log ", recordDir, phoneInfoUploadCtrl.filelist[0]);
        dbgprintf(DEBUG_ERROR, stderr, "rm file  %s\n", cmd);
        phoneInfoUploadCtrl.listSize--;
        int i = 0;
        for (; i < phoneInfoUploadCtrl.listSize - 1; i++)
        {
            memset(phoneInfoUploadCtrl.filelist[i], 0, 128);
            strcpy(phoneInfoUploadCtrl.filelist[i], phoneInfoUploadCtrl.filelist[i + 1]);         
        }
        strcpy(phoneInfoUploadCtrl.filelist[MAX_RECORD - 1], phoneInfoUploadCtrl.fileName);
        system(cmd);
    }
    else
    {
        memset(phoneInfoUploadCtrl.filelist[phoneInfoUploadCtrl.listSize - 1], 0, 128);
        strcpy(phoneInfoUploadCtrl.filelist[phoneInfoUploadCtrl.listSize - 1], phoneInfoUploadCtrl.fileName);
    
    }
    pthread_mutex_unlock(&counter_mutex);
    return RC_OK;
}




RESULT DATAUPLOAD_initUploadCtrl()
{
    DIR *pDir = NULL;
    sprintf(recordDir, "%s%s", data_storage_path, upload_path);
    pDir = opendir(recordDir);
    if (pDir == NULL) 
    {
        if (mkdir(recordDir, 0777) != 0)
        {
            dbgprintf(DEBUG_ERROR, stderr, "create upload dir %s falied\n", recordpath);
            return RC_FAIL;
        }
    }
    else
        closedir(pDir);
    system("rm /mnt/usr/upload/* -rf");
    DATAUPLOAD_getMAC("eth1", phoneInfoUploadCtrl.devMac, phoneInfoUploadCtrl.uploadMac);
    strcpy(phoneInfoUploadCtrl.srcMac,"11:22:11:11:11:11");
    int i = 0;
    for (; i < MAX_RECORD; i++)
    {
        memset(phoneInfoUploadCtrl.filelist[i], 0, 128);
    }
    phoneInfoUploadCtrl.listSize = 0;
    return true;      

}

RESULT get_md5Sign(char *buf, char *data)
{
    char tmpbuf[256] = {0};
    sprintf(tmpbuf, "echo -n %s|md5sum|cut -d ' ' -f1", buf);
    system(tmpbuf);
    
    DATAUPLOAD_cmdRsp(tmpbuf, 1, data);

    data[32] = '\0';
    dbgprintf(DEBUG_INFO,stdout,"string is %s cmd is %s  md5 is  %s\n", buf,  tmpbuf, data);
    return RC_OK;
}

bool UploadData(char *buf)
{
    char data[1024] = {0};
    DATAUPLOAD_cmdRsp(buf, 1, data);
    if (strstr(data, "success"))
    {
        return true;
    }
    else 
        return false;

}

bool DATAUPLOAD_getUploadUrl()
{
    char url[256] = {0};
    char data[1024] = {0};
    char sign[33] = {0};
    char md5string[128] = {0};
    time_t now;
    time(&now);
    sprintf(md5string, "'%lu%s%s'", now, phoneInfoUploadCtrl.devMac, phoneInfoUploadCtrl.md5Key);
    dbgprintf(DEBUG_INFO,stdout,"md5string is %s\n", md5string);
    get_md5Sign(md5string, sign);
    sprintf(url, "curl %c%s?devMac=%12s&time=%lu&sign=%s%c",  '"',phoneInfoUploadCtrl.url, phoneInfoUploadCtrl.uploadMac, now, sign, '"');
    if (DATAUPLOAD_cmdRsp(url, 0, data))
    {
        if (strstr(data, "http") == NULL)
            return false;
        char *url = strtok(data, " ");
        dbgprintf(DEBUG_INFO, stdout, "Url is %s \n", data);
        if (url == NULL)
            return false;
        strcpy(phoneInfoUploadCtrl.uploadUrl, url);
        dbgprintf(DEBUG_INFO, stdout, "uploadUrl is %s \n", phoneInfoUploadCtrl.uploadUrl);
        return true;
    }
    return false;

}

void DATAUPLOAD_UploadCtrlTimeout(void *h)
{
    MOD_timerRestart(DataUploadTimer, UPLOADCTRL_TIMEOUT);
    if (phoneInfoUploadCtrl.fp == NULL)
        return ;
    fclose(phoneInfoUploadCtrl.fp);
    phoneInfoUploadCtrl.fp = NULL;
    memset(phoneInfoUploadCtrl.tarName , 0, 128);
    strcpy(phoneInfoUploadCtrl.tarName, phoneInfoUploadCtrl.fileName);
    memset(phoneInfoUploadCtrl.fileName , 0, 128);
    while ((dup2(STDOUT_FILENO, STDERR_FILENO)==-1) && (errno==EINTR))
    {
    };
    sem_post(&sem_upload);
        
}


RESULT DATAUPLOAD_savePhoneInfo(U64 uptime,char *imsirecord, char *imeirecord,char *tmsirecord, U8 slotId)
{
    if (phoneInfoUploadCtrl.fp == NULL)
        DATAUPLOAD_openFile();
    if (phoneInfoUploadCtrl.fp != NULL)
    {
        fprintf(phoneInfoUploadCtrl.fp, "%s\t%s\t%llu\t%d\t%s\t%s\t%s\r\n", phoneInfoUploadCtrl.devMac, phoneInfoUploadCtrl.srcMac, uptime, slotId, imeirecord, imsirecord, tmsirecord);
         
        fflush(phoneInfoUploadCtrl.fp);
        return RC_OK;
    }
    return RC_FAIL;
}
#endif

#ifdef FTP

bool checkConnectServer()
{
    char cmd[128] = {0};
    sprintf(cmd, "ping -c 1 %s", phoneInfoUploadCtrl.addr);
    char data[1024] = {0};
    DATAUPLOAD_cmdRsp(cmd, 1, data);
    if (strstr(data, "time="))
    {
        int time1 = atoi(strstr(data, "time=")+5);
        dbgprintf(DEBUG_INFO, stdout, "time  is %d ms \n", time1);
        if (time1 > 10000)
            return false;
        return true;
    }
    return false;
}

RESULT DATAUPLOAD_openFile()
{
    time_t now;
  
    time(&now);
    struct tm *p = gmtime(&now);
    //localtime_t(&now, &p);
    phoneInfoUploadCtrl.startTm = now;
    if (strlen(phoneInfoUploadCtrl.devId) <= 1)
        return RC_FAIL;
    memset(phoneInfoUploadCtrl.fileName, 0, 128);
    sprintf(phoneInfoUploadCtrl.fileName, "Hotpoint_0_%s_0_%d%02d%02d%02d%02d%02d",phoneInfoUploadCtrl.devId,
            (1900+p->tm_year), (1 + p->tm_mon), p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec);
    memset(recordpath, 0, PATH_MAX);
    sprintf(recordpath, "%s/%s.hp", recordDir, phoneInfoUploadCtrl.fileName);
    phoneInfoUploadCtrl.fp = fopen(recordpath, "a");
    if (phoneInfoUploadCtrl.fp == NULL)
    {
        dbgprintf(DEBUG_ERROR, stderr, "can not open file  %s \n", recordpath);
        return RC_FAIL;
    }
    return RC_OK;
}


RESULT DATAUPLOAD_initUploadCtrl()
{
    DIR *pDir = NULL;
    sprintf(recordDir, "%s%s", data_storage_path, upload_path);
    pDir = opendir(recordDir);
    if (pDir == NULL) 
    {
        if (mkdir(recordDir, 0777) != 0)
        {
            dbgprintf(DEBUG_ERROR, stderr, "create upload dir %s falied\n", recordpath);
            return RC_FAIL;
        }
    }
    else
        closedir(pDir);
    system("rm /mnt/usr/upload/* -rf");
    DATAUPLOAD_getMAC("eth1", phoneInfoUploadCtrl.devMac, phoneInfoUploadCtrl.Mac); 
    return true;      
}

void DATAUPLOAD_UploadCtrlTimeout(void *h)
{
    MOD_timerRestart(DataUploadTimer, UPLOADCTRL_TIMEOUT);
    sem_post(&sem_upload);
}

RESULT DATAUPLOAD_savePhoneInfo(U64 uptime,char *imsirecord, char *imeirecord,char *tmsirecord, U8 slotId)
{  
    pthread_mutex_lock(&counter_mutex);
    if (phoneInfoUploadCtrl.fp == NULL)
        DATAUPLOAD_openFile();
    if (uptime - phoneInfoUploadCtrl.startTm >= MAX_RECORD_TIME)
    {
        fclose(phoneInfoUploadCtrl.fp);
        phoneInfoUploadCtrl.fp = NULL;
        system("rm /mnt/usr/upload/* -rf");
        while ((dup2(STDOUT_FILENO, STDERR_FILENO)==-1) && (errno==EINTR))
        {
        };
        DATAUPLOAD_openFile();
    }
    if (phoneInfoUploadCtrl.fp != NULL)
    {
        switch(slotId)
        {
            case 1:
                   fprintf(phoneInfoUploadCtrl.fp, "%s40\t%s\t%s\t\t%llu\t1\r\n", phoneInfoUploadCtrl.devId, imsirecord, imeirecord, uptime);
                   break;
            case 2:
                   fprintf(phoneInfoUploadCtrl.fp, "%s42\t%s\t%s\t\t%llu\t1\r\n", phoneInfoUploadCtrl.devId, imsirecord, imeirecord, uptime);
                   break;
            case 3:
                   fprintf(phoneInfoUploadCtrl.fp, "%s41\t%s\t%s\t\t%llu\t1\r\n", phoneInfoUploadCtrl.devId, imsirecord, imeirecord, uptime);
                   break;
            case 4:
            case 5:
                   fprintf(phoneInfoUploadCtrl.fp, "%s40\t%s\t%s\t\t%llu\t1\r\n", phoneInfoUploadCtrl.devId, imsirecord, imeirecord, uptime);
                   break;
            case 6:
                   fprintf(phoneInfoUploadCtrl.fp, "%s47\t%s\t%s\t\t%llu\t1\r\n", phoneInfoUploadCtrl.devId, imsirecord, imeirecord, uptime);
                   break; 
            case 7:
                   fprintf(phoneInfoUploadCtrl.fp, "%s44\t%s\t%s\t\t%llu\t1\r\n", phoneInfoUploadCtrl.devId, imsirecord, imeirecord, uptime);
                   break;
            case 8:
                   fprintf(phoneInfoUploadCtrl.fp, "%s20\t%s\t%s\t\t%llu\t1\r\n", phoneInfoUploadCtrl.devId, imsirecord, imeirecord, uptime);
                   break;
            
            case 9:
                   fprintf(phoneInfoUploadCtrl.fp, "%s22\t%s\t%s\t\t%llu\t1\r\n", phoneInfoUploadCtrl.devId, imsirecord, imeirecord, uptime);
                   break;
            
             default:
                   break;

        }         

        fflush(phoneInfoUploadCtrl.fp);
        pthread_mutex_unlock(&counter_mutex);
        return RC_OK;
    }
    pthread_mutex_unlock(&counter_mutex);
    return RC_FAIL;
}

#endif


void DATAUPLOAD_setProc(PCMDHEADER pCmd, PCMDHEADER pAck)
{
    switch(pCmd->cmdCode)
    {
        case  CMD_CODE_CONFIG_DATAUPLOAD:
              {                      
                  UNPACK_RESULT uprc;
                  PPARAM pParam =(PPARAM)(pCmd+1);
                  uint32_t paraType;
                  uint32_t paraLength;
                  uint8_t* paraValue = NULL;
                  bool isParaValid = true;
                  uint32_t len = pCmd->cmdLength; 
                  while((uprc=CM_paraUnpackPara(&pParam, &len, &paraType, &paraLength,&paraValue)) == UNPACK_OK)
                  {
#ifdef HTTP
                      if( paraType==PARA_TYPE_DATAUPLOAD_PLACE)
                      {
                          memset(phoneInfoUploadCtrl.place, 0, 16);
                          memcpy(phoneInfoUploadCtrl.place, paraValue, paraLength);
                          dbgprintf(DEBUG_INFO, stdout, "upload place  is %s \n ", phoneInfoUploadCtrl.place);
                      }
                      else if( paraType==PARA_TYPE_DATAUPLOAD_DATATYPE )
                      {
                          memset(phoneInfoUploadCtrl.dataType, 0, 16);
                          memcpy(phoneInfoUploadCtrl.dataType, paraValue, paraLength);
                          dbgprintf(DEBUG_INFO, stdout, "upload datatype is %s \n ", phoneInfoUploadCtrl.dataType);
                      }
                      else if( paraType==PARA_TYPE_DATAUPLOAD_PROTOCOL )
                      {
                          memset(phoneInfoUploadCtrl.protocol, 0, 16);
                          memcpy(phoneInfoUploadCtrl.protocol, paraValue, paraLength);
                          dbgprintf(DEBUG_INFO, stdout, "upload protocol is %s \n ", phoneInfoUploadCtrl.protocol);
                      }
                      else if( paraType==PARA_TYPE_DATAUPLOAD_MD5KEY )
                      {
                          memset(phoneInfoUploadCtrl.md5Key, 0, 128);
                          memcpy(phoneInfoUploadCtrl.md5Key, paraValue, paraLength);
                          dbgprintf(DEBUG_INFO, stdout, "upload md5key is %s \n ", phoneInfoUploadCtrl.md5Key);
                      }
                      else if( paraType==PARA_TYPE_DATAUPLOAD_URL )
                      {
                          memset(phoneInfoUploadCtrl.url, 0, 128);
                          memcpy(phoneInfoUploadCtrl.url, paraValue, paraLength);
                          dbgprintf(DEBUG_INFO, stdout, "upload url is %s \n ", phoneInfoUploadCtrl.url);
                      }
                      else
                      {
                          dbgprintf(DEBUG_ERROR, stderr, "unkonw type is %d \n ", paraType);
                          isParaValid = false;
                      }
#endif 

#ifdef FTP
                      if( paraType==PARA_TYPE_DATAUPLOAD_DEVID)
                      {
                          memset(phoneInfoUploadCtrl.devId, 0, 18);
                          memcpy(phoneInfoUploadCtrl.devId, paraValue, paraLength);
                          dbgprintf(DEBUG_INFO, stdout, "upload devId  is %s \n ", phoneInfoUploadCtrl.devId);
                      }
                      else if( paraType==PARA_TYPE_DATAUPLAOD_ADDR )
                      {
                          memset(phoneInfoUploadCtrl.addr, 0, 128);
                          memcpy(phoneInfoUploadCtrl.addr, paraValue, paraLength);
                          dbgprintf(DEBUG_INFO, stdout, "upload addr is %s \n ", phoneInfoUploadCtrl.addr);
                      }
                      else if( paraType==PARA_TYPE_DATAUPLOAD_PORT )
                      {
                          memset(phoneInfoUploadCtrl.port, 0, 16);
                          memcpy(phoneInfoUploadCtrl.port, paraValue, paraLength);
                          dbgprintf(DEBUG_INFO, stdout, "upload port is %s \n ", phoneInfoUploadCtrl.port);
                      }
                      else if( paraType==PARA_TYPE_DATAUPLOAD_USER )
                      {
                          memset(phoneInfoUploadCtrl.usr, 0, 128);
                          memcpy(phoneInfoUploadCtrl.usr, paraValue, paraLength);
                          dbgprintf(DEBUG_INFO, stdout, "upload usr is %s \n ", phoneInfoUploadCtrl.usr);
                      }
                      else if( paraType==PARA_TYPE_DATAUPLOAD_PASSWORD )
                      {
                          memset(phoneInfoUploadCtrl.pwd, 0, 128);
                          memcpy(phoneInfoUploadCtrl.pwd, paraValue, paraLength);
                          dbgprintf(DEBUG_INFO, stdout, "upload pwd is %s \n ", phoneInfoUploadCtrl.pwd);
                      }
                      else if( paraType==PARA_TYPE_DATAUPLOAD_COMMOND )
                      {
                          memset(phoneInfoUploadCtrl.commond, 0, 128);
                          memcpy(phoneInfoUploadCtrl.commond, paraValue, paraLength);
                          dbgprintf(DEBUG_INFO, stdout, "upload commond is %s \n ", phoneInfoUploadCtrl.commond);
                      }
                      else
                      {
                          dbgprintf(DEBUG_ERROR, stderr, "unkonw type is %d \n ", paraType);
                          isParaValid = false;
                      }


#endif

                 }
                 if (isParaValid)
                 {
                     pAck->cmdLength = CM_paraPackU32((PPARAM)(pAck+1), PARA_TYPE_RESULT,PARA_VALUE_RESULT_SUCCESS);   
                 }
                 else
                     pAck->cmdLength = CM_paraPackError((PPARAM)(pAck+1), PARA_VALUE_ERROR_UNKNOWN_PARATYPE);
            }
            break;     

            
        default:
            pAck->cmdLength = CM_paraPackError((PPARAM)(pAck+1), PARA_VALUE_ERROR_UNKNOWN_CMDCODE);
            dbgprintf(DEBUG_ERROR,stderr,"Unknown SET cmd cmdCode=%04x\n",pCmd->cmdCode);
            break;
    }

}

void DATAUPLOAD_getProc(PCMDHEADER pCmd, PCMDHEADER pAck)
{
    switch(pCmd->cmdCode)
    {
        
        default:
            pAck->cmdLength = CM_paraPackError((PPARAM)(pAck+1), PARA_VALUE_ERROR_UNKNOWN_CMDCODE);            
            dbgprintf(DEBUG_ERROR,stderr,"Unknown GET cmd cmdCode=%04x\n",pCmd->cmdCode);
            break;        
    }

}


//for indication, error do nothing
void DATAUPLOAD_ueIDReport(PCMDHEADER pCmd)
{

    UEIDPARALIST paraList = {0};
   
    if(RC_OK == CM_paraListDecoder(pCmd,NULL, UEIDReportTable,sizeof(UEIDReportTable)/sizeof(PARADECODERMAP),&paraList,TRUE))
    {
        if(paraList.uptime == 0)
        {
            dbgprintf(DEBUG_ERROR,stderr,"Error in cmdType=%02x cmdCode=%04x. Error=%x\n",pCmd->cmdType,pCmd->cmdCode,PARA_VALUE_ERROR_NOT_ENOUGH_PARA);
            return;
        }
        
        DATAUPLOAD_savePhoneInfo(paraList.uptime,paraList.imsirecord, paraList.imeirecord,NULL, paraList.slotId);       

    }
    
}

void DATAUPLOAD_eventProc(PCMDHEADER pCmd)
{
    switch(pCmd->cmdCode)
    {
        //case CMD_GSM_EVT_PHONE:
        case CMD_EVT_EUTRAN_UEID:
            
            DATAUPLOAD_ueIDReport(pCmd);
            break;
        default:
            dbgprintf(DEBUG_ERROR,stderr,"Unknown EVENT cmdCode=%04x\n",pCmd->cmdCode);            
            break;
        

    }

}

void DATAUPLOAD_eventAckProc(PCMDHEADER pCmd)
{
    

    switch(pCmd->cmdCode)
    {
  
        default:
            dbgprintf(DEBUG_ERROR,stderr,"Unknown EVENT cmdCode=%04x\n",pCmd->cmdCode);            
            break;
        

    }

}

void DATAUPLOAD_postProc(void)
{

    if(needPostProc)
    {        
        needPostProc = FALSE;

    }
        
}


void* DATAUPLOAD_main(void*h)
{
	CMMODINFO cmModInfo = {0};
    pthread_setname_np(pthread_self(), "dataHandle");

    cmModInfo.ModID = MODULE_DATAUPLOAD;
    cmModInfo.useTimer = TRUE;
    cmModInfo.setProc = DATAUPLOAD_setProc;
    cmModInfo.getProc = DATAUPLOAD_getProc;
    cmModInfo.eventProc = DATAUPLOAD_eventProc;    
    cmModInfo.eventAckProc = DATAUPLOAD_eventAckProc;    
    cmModInfo.postProc = DATAUPLOAD_postProc;
    DataUploadTimer = MOD_timerStart(MODULE_DATAUPLOAD, UPLOADCTRL_TIMEOUT, DATAUPLOAD_UploadCtrlTimeout, NULL);
    CM_cmdDispatcher(&cmModInfo);

    
    return NULL;

}



void* upload_main(void*h)
{
    pthread_setname_np(pthread_self(), "dataUpload");
    char cmd[256] = {0};
#ifdef HTTP
    char rmcmd[256] = {0};
    char md5string[256] = {0};
    char sign[33] = {0};
    bool rsp = false;
#endif
#ifdef FTP
    int rsp = 0;

#endif
    while(1)
    {
        sem_wait(&sem_upload);
#ifdef HTTP
        if (DATAUPLOAD_getUploadUrl())
        {
            char cmd1[256] = {0};
            if (phoneInfoUploadCtrl.fp != NULL)
                sprintf(cmd1, "cd %s && zip -q -r %s.zip  `ls |grep -v %s`", recordDir, phoneInfoUploadCtrl.tarName, phoneInfoUploadCtrl.fileName);
            else
                sprintf(cmd1, "cd %s && zip -q -r %s.zip  *", recordDir, phoneInfoUploadCtrl.tarName);
            system(cmd1);
            
        }
        else
            continue;
        memset(md5string, 0, 256);
        sprintf(md5string, "'%s%s%s.zip%s'", phoneInfoUploadCtrl.dataType, phoneInfoUploadCtrl.protocol, phoneInfoUploadCtrl.tarName, phoneInfoUploadCtrl.md5Key);
        get_md5Sign(md5string, sign);

        memset(cmd, 0, 256);
        memset(rmcmd, 0, 256);
        sprintf(cmd, "curl -s --retry 1 --connect-timeout 5 -m 90 -F 'file=@%s/%s.zip' '%s?dataType=imei&protocol=imei&sign=%s'",
                recordDir, phoneInfoUploadCtrl.tarName, phoneInfoUploadCtrl.uploadUrl, sign);
        rsp = UploadData(cmd);
        dbgprintf(DEBUG_INFO,stdout,"upload data cmd is %s \n", cmd); 
        if (rsp)
        {
            if (phoneInfoUploadCtrl.fp != NULL)
                sprintf(rmcmd, "cd %s && rm `ls |grep -v %s` && cd /usr/bin", recordDir, phoneInfoUploadCtrl.fileName );
            else
                sprintf(rmcmd, "rm %s/* ", recordDir);
            pthread_mutex_lock(&counter_mutex);
            phoneInfoUploadCtrl.listSize = 0;
            pthread_mutex_unlock(&counter_mutex);
        }
        else
            sprintf(rmcmd, "rm   %s/%s.zip", recordDir, phoneInfoUploadCtrl.tarName);
        dbgprintf(DEBUG_INFO,stdout,"upload data rmcmd is %s rsp is %d \n", rmcmd, rsp); 
        system(rmcmd);
#endif
#ifdef FTP
        
        if (phoneInfoUploadCtrl.fp  != NULL)
        {
            pthread_mutex_lock(&counter_mutex);
            fclose(phoneInfoUploadCtrl.fp);
            phoneInfoUploadCtrl.fp = NULL;
           
            while ((dup2(STDOUT_FILENO, STDERR_FILENO)==-1) && (errno==EINTR))
            {
            };
            pthread_mutex_unlock(&counter_mutex);
        
       
            if (strlen(phoneInfoUploadCtrl.addr) >= 6 && checkConnectServer())
            {
                sprintf(cmd, "curl -u %s:%s -T %s ftp://%s:%s ", phoneInfoUploadCtrl.usr, phoneInfoUploadCtrl.pwd, recordpath, phoneInfoUploadCtrl.addr, phoneInfoUploadCtrl.port);
                rsp = system(cmd);
                dbgprintf(DEBUG_INFO,stdout,"upload data cmd is %s rsp is %d \n", cmd, rsp); 
            }

            system("rm /mnt/usr/upload/* -rf");
        }
#endif
    }

}


RESULT DATAUPLOAD_init(void)
{
	pthread_t pthrd;
    pthread_t uploadPthrd;
    MODREG modReg = {0};

    
    needPostProc = FALSE;
    
    DATAUPLOAD_initUploadCtrl();

    
    modReg.modID = MODULE_DATAUPLOAD;
    modReg.needTick = TRUE;
    modReg.tickPeriod = DATAUPLOAD_TIMER_RESOLUTION; // 1s
    modReg.needModTimer = TRUE;

    MOD_register(&modReg);
    signal(SIGCHLD, SIG_IGN);
    pthread_create(&pthrd, NULL, DATAUPLOAD_main, NULL);

    sem_init(&sem_upload, 0, 1);
    sem_wait(&sem_upload);
    pthread_create(&uploadPthrd, NULL, upload_main, NULL);
    return RC_OK;


}



